package org.bhf.service.view;

import org.bhf.i18n.Message;
import org.bhf.json.JSONWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A <code>ProcessView</code> to set the status to <code>HTTP_INTERNAL_ERROR</code> and return one or more localized
 * messages as the exception object.
 */
public class ErrorsProcessView extends JSONProcessView
{
    /**
     * With a single message.
     * @param message Must not be <code>null</oode>
     * @param exception The class name becomes the type fields of the JSON exception. May be <code>null</code>
     */
    public ErrorsProcessView( final Message message, final Throwable exception )
    {
        this( Arrays.asList( message ), exception );
    }

    /**
     * With a multiple messages.
     * @param messages Must not be <code>null</oode> or empty.
     * @param exception The class name becomes the type fields of the JSON exception. May be <code>null</code>
     */
    public ErrorsProcessView( final List<Message> messages, final Throwable exception )
    {
        super( new JSONWriter() );

        final List<Message> localizedMessages = new ArrayList<Message>( messages.size() );

        for( final Message message : messages )
        {
            localizedMessages.add( message.localize() );
        }
        setResult( new ErrorsException( localizedMessages, exception != null ? exception.getClass().getName() : "" ) );
    }

    /**
     * Process the view.
     * @param request Request
     * @param response Response
     * @param servletContext Context
     * @throws IOException Error writing the JSON object
     * @exclude
     */
    @Override
    public void processView( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext )
        throws IOException
    {
        response.setStatus( HttpURLConnection.HTTP_INTERNAL_ERROR );
        super.processView( request, response, servletContext );
    }

    public static class ErrorsException
    {
        final String        type;
        final List<Message> messages;

        public ErrorsException( List<Message> messages, String type )
        {
            this.type     = type;
            this.messages = messages;
        }

        public String getType()
        {
            return type;
        }

        public List<Message> getMessages()
        {
            return messages;
        }

    }
}
